package com.example.vueadminjava2.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

@Data
@Component
public class JwtUtils{

	private static String TOKEN = "gttt@W3e4r";
	/**
	 * 生成token
	 * @param map  //传入payload
	 * @return 返回token
	 */
	public static String getToken(Map<String,String> map){
		JWTCreator.Builder builder = JWT.create();
		map.forEach((k,v)->{
			builder.withClaim(k,v);
		});
		Calendar instance = Calendar.getInstance();
		instance.add(Calendar.HOUR,7*24);//设置过期时间
		builder.withExpiresAt(instance.getTime());
		return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
	}
	/**
	 * 验证token
	 * @param token
	 * @return
	 */
	public static void verify(String token){
		JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
	}
	/**
	 * 获取token中payload
	 * @param token
	 * @return
	 */
	public static DecodedJWT getToken(String token){
		return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
	}

}
